package top.codef.secure.handlers;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.codef.secure.config.interfaces.LogoutSuccessDecorator;
import top.codef.secure.pojomodel.SecureResponseEnum;
import top.codef.secure.properties.CerberusLogoutProperties;

public class CerberusLogoutSuccessHandler implements LogoutSuccessHandler {

	private final ObjectMapper objectMapper;

	private final Log logger = LogFactory.getLog(CerberusLogoutSuccessHandler.class);

	private final LogoutSuccessDecorator logoutSuccessDecorator;

	private final CerberusLogoutProperties cerberusLogoutProperties;

	public CerberusLogoutSuccessHandler(ObjectMapper objectMapper, LogoutSuccessDecorator logoutSuccessDecorator,
			CerberusLogoutProperties cerberusLogoutProperties) {
		this.objectMapper = objectMapper;
		this.logoutSuccessDecorator = logoutSuccessDecorator;
		this.cerberusLogoutProperties = cerberusLogoutProperties;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		logger.info("登出成功操作：" + authentication);
		var obj = logoutSuccessDecorator.decorate(request, response, authentication);
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.getWriter()
				.write(objectMapper.writeValueAsString(SecureResponseEnum.LOGOUT_SUCCESS.createSecureModel(
						cerberusLogoutProperties.getSuccessMessageStatus(),
						cerberusLogoutProperties.getSuccessMessage(), obj)));
		response.flushBuffer();
	}
}
